//
//  MineModifyInformationViewController.m
//  shuiyun
//
//  Created by 马田成 on 2017/9/5.
//  Copyright © 2017年 qianyi. All rights reserved.
//

#import "MineModifyInformationViewController.h"
#import "MineModifyTFTableViewCell.h"
#import "MineModifyFirstTableViewCell.h"

#import "STPhotoKitController.h"
#import "UIImagePickerController+ST.h"
#import "UIButton+AddAction.h"
#import "ICN_HeadImageSelView.h"



@interface MineModifyInformationViewController ()<UITableViewDelegate,UITableViewDataSource,UIImagePickerControllerDelegate,STPhotoKitDelegate,UINavigationControllerDelegate,UITextFieldDelegate>
{
    
    UIView *grayView;

    MineModifyFirstTableViewCell *cellImage;
    MineModifyTFTableViewCell *usernameCell;//名字
    MineModifyTFTableViewCell *phoneCell;//电话
    
    MineModifyTFTableViewCell *ocipCell;//qq
    MineModifyTFTableViewCell *addressCell;//address
    MineModifyTFTableViewCell *shenCell;//省
    MineModifyTFTableViewCell *chcmCell;//船舶船名
    MineModifyTFTableViewCell *cbdwCell;//船舶吨位
    MineModifyTFTableViewCell *hxstartCell;//始发港
    MineModifyTFTableViewCell *hxendCell;//到达港
}
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, strong) NSMutableDictionary *productParams;


@property (nonatomic, strong) UIImage *image;
@property (nonatomic, strong) NSData *imageData;

@property (nonatomic, strong) ICN_HeadImageSelView *changeHeadImageView;



@property (nonatomic, strong) NSMutableDictionary *dataDit;




@end

@implementation MineModifyInformationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self creationData];
    [self creationView];
    [self regeditCell];

    
}
- (void)creationView{
    
    self.tableView = [[UITableView alloc] init];
    self.tableView.frame = CGRectMake(0, 0, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT - 64);
    self.tableView.tableFooterView = [[UITableView alloc] initWithFrame:CGRectZero];
    
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.separatorStyle = UITableViewCellAccessoryNone;//去掉分割线
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    [self setTitle:@"修改信息"];
    
    UIButton *buttonAdd = [[UIButton alloc] init];
    
    buttonAdd.frame = CGRectMake(DEF_SCREEN_WIDTH - 40, 0, 40, 40);
    
    
    [buttonAdd setTitle:@"完成" forState:UIControlStateNormal];
    
    [buttonAdd addTarget:self action:@selector(sureClick) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *rightItme = [[UIBarButtonItem alloc]initWithCustomView:buttonAdd];
    self.navigationItem.rightBarButtonItem = rightItme;

    
}
- (void)regeditCell{
    
    
    
    [self.tableView registerNib:[UINib nibWithNibName:@"MineModifyFirstTableViewCell" bundle:nil] forCellReuseIdentifier:@"MineModifyFirstTableViewCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"MineModifyTFTableViewCell" bundle:nil] forCellReuseIdentifier:@"MineModifyTFTableViewCell"];
    
    
}

//获取
- (void)creationData{
    
    _dataDit = [[NSMutableDictionary alloc] init];
    
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[[UIApplication sharedApplication]keyWindow] animated:YES];
    hud.tag = 500;
    //提示文本
    hud.labelText = @"正在加载...";
    //是否有遮罩
    hud.dimBackground = YES;
    NSMutableDictionary *productParams=[[NSMutableDictionary alloc]init];
    
    NSString *token = [PublicFunction getConfigWithKey:@"token"];
    //    NSString *str = @"917b0ddccade4345b1b066fdc4971a14";
    NSString *userid = [PublicFunction getConfigWithKey:@"userid"];
    
    [productParams setValue:userid forKey:@"userid"];
    
    [productParams setValue:token forKey:@"token"];
    
    [[MNetworkHandler sharedInstance]conURL:hometPersonalPerson networkType:NetWorkPOST params:productParams delegate:nil showHUD:NO successBlock:^(id returnData) {
        
        if ([[returnData objectForKey:@"code"]intValue]==1) {
            
            _dataDit = [returnData objectForKey:@"data"];
            
            
            NSLog(@"MMMMMMMMMM%@", _dataDit);
            [self.view addSubview:self.tableView];
            [self.tableView reloadData];
            
            
            [hud removeFromSuperview];
        }
        
        else {
            
            [PublicFunction showAlert:nil message:[returnData objectForKey:@"msg"] duration:5.0f];
            [hud removeFromSuperview];
            
        }
        
    } failureBlock:^(NSError *error) {
        
        NSLog(@"%@",error);
        
        [PublicFunction showAlert:nil message:@"没有连接网络" duration:10.0f];
        [hud removeFromSuperview];
    }];
    
}


//上传
-(void)modifyMessages{

    self.productParams=[[NSMutableDictionary alloc]init];
    NSString *token = [PublicFunction getConfigWithKey:@"token"];
    [self.productParams setValue:token forKey:@"token"];
    NSString * userid = [PublicFunction getConfigWithKey:@"userid"];
    [self.productParams setValue:userid forKey:@"userid"];
    
    [self.productParams setValue:usernameCell.contentTF.text forKey:@"username"];
    [self.productParams setValue:phoneCell.contentTF.text forKey:@"phone"];
    [self.productParams setValue:ocipCell.contentTF.text forKey:@"ocip"];
    [self.productParams setValue:shenCell.contentTF.text forKey:@"shen"];
    [self.productParams setValue:addressCell.contentTF.text forKey:@"address"];
    [self.productParams setValue:chcmCell.contentTF.text forKey:@"chcm"];
    [self.productParams setValue:cbdwCell.contentTF.text forKey:@"cbdw"];
    [self.productParams setValue:hxstartCell.contentTF.text forKey:@"hxstart"];

    [self.productParams setValue:hxendCell.contentTF.text forKey:@"hxend"];
    
    
    /*方式一：使用NSData数据流传图片*/
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                         @"text/plain",
                                                         @"text/javascript",
                                                         @"text/json",
                                                         @"text/html",
                                                         @"image/jpeg", nil];
    [manager POST:modifyMessage parameters:self.productParams constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        
        
        if (self.image) {
            
            self.imageData = UIImageJPEGRepresentation(self.image,0.005);
        }else {
            
            self.imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"添加头像"],0.005);
            
        }
        
        
        //压缩图片
        
        //拼接图片名称+时间确保不重复命名
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *imageFileName = [NSString stringWithFormat:@"%@.jpg", [formatter stringFromDate:[NSDate date]]];
        // 测试输出文件名
        
        //上传图片，以文件流的格式sdf
        
        //        [formData appendPartWithFileData:UIImageJPEGRepresentation([UIImage imageNamed:@"1"], 5.0) name:@"image1" fileName:@"1.jpg" mimeType:@"image/jpeg"];
        
        [formData appendPartWithFileData:_imageData name:@"titlepic" fileName:imageFileName mimeType:@"image/JPG"];
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSString *strtmp = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSString *requestTmp = [NSString stringWithString: strtmp];
        NSData *resData = [[NSData alloc] initWithData:[requestTmp dataUsingEncoding:NSUTF8StringEncoding]];
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:resData options:NSJSONReadingMutableLeaves error:nil];  //解析
        NSLog(@"+++>%@", resultDic);
        NSLog(@"--->%@", resultDic[@"msg"]);
        
        
        if ([[resultDic objectForKey:@"code"]intValue]==1) {
            
            
            //NSLog(@"!!!!!!!!!!!!!!!%@",_dataArr);
            
            [PublicFunction showAlert:nil message:@"发布成功" duration:10.0f];
                        
            [self.navigationController popViewControllerAnimated:YES];
        }
        
        else {
            
            [PublicFunction showAlert:nil message:[resultDic objectForKey:@"msg"] duration:5.0f];
            
        }
        
        
        
        
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"%@",error);
        
        [PublicFunction showAlert:nil message:@"没有连接网络" duration:10.0f];
    }];
    
}
#pragma mark - ---------- Section的数量 ----------
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
#pragma mark - ---------- 每个Section的高度 ----------
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0;
}

//section 不随tableView滑动
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    if (scrollView == self.tableView)
        
    {
        
        CGFloat sectionHeaderHeight = 64; //header高度
        
        if (scrollView.contentOffset.y <= sectionHeaderHeight && scrollView.contentOffset.y >= 0) {
            
            scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
            
        } else if (scrollView.contentOffset.y >= sectionHeaderHeight) {
            
            scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
            
        }
        
    }
  
}


#pragma mark - ---------- Cell的数量 ----------
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    
    return 10;
    
}

#pragma mark - ---------- 每个Cell的高度 ----------
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.row == 0) {
        return 110;
    }else {
        
        return 43;
    }
    
}
#pragma mark - ---------- 每个Cell的内容 ----------
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == 0) {
        
        cellImage = [self.tableView dequeueReusableCellWithIdentifier:@"MineModifyFirstTableViewCell" forIndexPath:indexPath];
          cellImage.selectionStyle = UITableViewCellSelectionStyleNone;
        
        if ([[_dataDit objectForKey:@"titlepic"] length] == 0) {
            cellImage.iconImageview.image = [UIImage imageNamed:@"添加头像"];
            
            
        }else {
        
            NSString *urlVpPic1 = manage(AP_HOST, [_dataDit objectForKey:@"titlepic"]);
            
            [cellImage.iconImageview sd_setImageWithURL:[NSURL URLWithString:urlVpPic1] placeholderImage:[UIImage imageNamed:@""]];
        }
        
        return cellImage;
        
    }
        
    
    if (indexPath.row == 1) {
        
        usernameCell = [self.tableView dequeueReusableCellWithIdentifier:@"MineModifyTFTableViewCell" forIndexPath:indexPath];
            
        
        usernameCell.selectionStyle = UITableViewCellSelectionStyleNone;
//            NSArray *arr = @[,@"手机号码",@"QQ号码",@"船名船号",@"船舶吨位",@"始发港",@"到达港",@"所在省市",@"街道地址"];
        
        usernameCell.leftLabel.text = @"真实姓名";
        
        usernameCell.contentTF.placeholder = [_dataDit objectForKey:@"username"];
        return usernameCell;
        
       
            
            
        }else if (indexPath.row ==2){
        
            
            phoneCell = [self.tableView dequeueReusableCellWithIdentifier:@"MineModifyTFTableViewCell" forIndexPath:indexPath];
            
            phoneCell.selectionStyle = UITableViewCellSelectionStyleNone;
           ;
            phoneCell.leftLabel.text = @"手机号码";
            phoneCell.contentTF.placeholder = [_dataDit objectForKey:@"phone"];
            return phoneCell;
            
        }else if (indexPath.row ==3){
            
            ocipCell = [self.tableView dequeueReusableCellWithIdentifier:@"MineModifyTFTableViewCell" forIndexPath:indexPath];
            
            ocipCell.selectionStyle = UITableViewCellSelectionStyleNone;
           
            ocipCell.leftLabel.text = @"QQ号码";
            ocipCell.contentTF.placeholder = [_dataDit objectForKey:@"ocip"];

            return ocipCell;
            
            
        }else if (indexPath.row ==4){
            
            chcmCell = [self.tableView dequeueReusableCellWithIdentifier:@"MineModifyTFTableViewCell" forIndexPath:indexPath];
            
            chcmCell.selectionStyle = UITableViewCellSelectionStyleNone;
    
            chcmCell.leftLabel.text = @"船名船号";
            chcmCell.contentTF.placeholder = [_dataDit objectForKey:@"chcm"];
            return chcmCell;
            
            
        }else if (indexPath.row ==5){
            
            cbdwCell = [self.tableView dequeueReusableCellWithIdentifier:@"MineModifyTFTableViewCell" forIndexPath:indexPath];
            
            cbdwCell.selectionStyle = UITableViewCellSelectionStyleNone;
            //            NSArray *arr = @[,@"手机号码",@"QQ号码",@"船名船号",@"船舶吨位",@"始发港",@"到达港",@"所在省市",@"街道地址"];
            cbdwCell.leftLabel.text = @"船舶吨位";
            cbdwCell.contentTF.placeholder = [_dataDit objectForKey:@"cbdw"];
            
            return cbdwCell;
            

            
        }else if (indexPath.row ==6){
            
            hxstartCell = [self.tableView dequeueReusableCellWithIdentifier:@"MineModifyTFTableViewCell" forIndexPath:indexPath];
            
            hxstartCell.selectionStyle = UITableViewCellSelectionStyleNone;
            //            NSArray *arr = @[,@"手机号码",@"QQ号码",@"船名船号",@"船舶吨位",@"始发港",@"到达港",@"所在省市",@"街道地址"];
            hxstartCell.leftLabel.text = @"始发港";
            hxstartCell.contentTF.placeholder = [_dataDit objectForKey:@"hxstart"];
            
            return hxstartCell;
        }else if (indexPath.row ==7){
            
            hxendCell = [self.tableView dequeueReusableCellWithIdentifier:@"MineModifyTFTableViewCell" forIndexPath:indexPath];
            
            hxendCell.selectionStyle = UITableViewCellSelectionStyleNone;
            //            NSArray *arr = @[,@"手机号码",@"QQ号码",@"船名船号",@"船舶吨位",@"始发港",@"到达港",@"所在省市",@"街道地址"];
            hxendCell.leftLabel.text = @"到达港";
            hxendCell.contentTF.placeholder = [_dataDit objectForKey:@"hxend"];
            
            return hxendCell;
        }else if (indexPath.row ==8){
            
            shenCell = [self.tableView dequeueReusableCellWithIdentifier:@"MineModifyTFTableViewCell" forIndexPath:indexPath];
            
            shenCell.selectionStyle = UITableViewCellSelectionStyleNone;
            //            NSArray *arr = @[,@"手机号码",@"QQ号码",@"船名船号",@"船舶吨位",@"始发港",@"到达港",@"所在省市",@"街道地址"];
            shenCell.leftLabel.text = @"所在省市";
            shenCell.contentTF.placeholder = [_dataDit objectForKey:@"shen"];
            
            return shenCell;
        }else {
            
            addressCell = [self.tableView dequeueReusableCellWithIdentifier:@"MineModifyTFTableViewCell" forIndexPath:indexPath];
            
            addressCell.selectionStyle = UITableViewCellSelectionStyleNone;
            //            NSArray *arr = @[,@"手机号码",@"QQ号码",@"船名船号",@"船舶吨位",@"始发港",@"到达港",@"所在省市",@"街道地址"];
            addressCell.leftLabel.text = @"街道地址";
            addressCell.contentTF.placeholder = [_dataDit objectForKey:@"address"];
            
            return addressCell;
            
            
        }
        
   
    
    
}
#pragma mark - ---------- 每个Cell的点击事件 ----------
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        
        grayView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT)];
        grayView.backgroundColor = [UIColor colorWithRed:0 / 255.0f green:0 / 255.0f blue:0 / 255.0f alpha:0.2];
        
        [[UIApplication sharedApplication].keyWindow addSubview:grayView];
        
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissContactView)];
        [grayView addGestureRecognizer:tapGesture];
        
        [grayView addSubview:self.changeHeadImageView];
        [self.changeHeadImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.mas_equalTo(self.view);
            make.size.mas_equalTo(CGSizeMake(DEF_SCREEN_WIDTH, 160));
        }];
        
        self.changeHeadImageView.layer.cornerRadius = 8;
        [self.changeHeadImageView.takePhotoButton addAction:^(NSInteger tag) {
            UIImagePickerController *controller = [UIImagePickerController imagePickerControllerWithSourceType:UIImagePickerControllerSourceTypeCamera];
            [grayView removeFromSuperview];
            if ([controller isAvailableCamera] && [controller isSupportTakingPhotos]) {
                [controller setDelegate:self];
                [self presentViewController:controller animated:YES completion:nil];
            }else {
                NSLog(@"%s %@", __FUNCTION__, @"相机权限受限");
            }
        }];
        [self.changeHeadImageView.localAlbumButton addAction:^(NSInteger tag) {
            UIImagePickerController *controller = [UIImagePickerController imagePickerControllerWithSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
            [controller setDelegate:self];
            [grayView removeFromSuperview];
            if ([controller isAvailablePhotoLibrary]) {
                [self presentViewController:controller animated:YES completion:nil];
            }
        }];
        [self.changeHeadImageView.closeViewButton addAction:^(NSInteger tag) {
            [self dismissContactView];
        }];
        
    }

}


#pragma mark ----------------------- 相册／相机 ---------------------

- (void)photoKitController:(STPhotoKitController *)photoKitController resultImage:(UIImage *)resultImage
{
    // [self.imageButton setImage:resultImage forState:UIControlStateNormal];
    
    
    self.image = resultImage;
    cellImage.iconImageview.image = resultImage;
    
    //    self.shoppicImage.image = resultImage;
    //self.headImage.image = resultImage;
    //[_headImg setImage:resultImage forState:UIControlStateNormal];
    
}

#pragma mark - 2.UIImagePickerController的委托

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    [picker dismissViewControllerAnimated:YES completion:^{
        UIImage *imageOriginal = [info objectForKey:UIImagePickerControllerOriginalImage];
        STPhotoKitController *photoVC = [STPhotoKitController new];
        [photoVC setDelegate:self];
        [photoVC setImageOriginal:imageOriginal];
        
        [photoVC setSizeClip:CGSizeMake(100 ,100)];
        
        
        [self presentViewController:photoVC animated:YES completion:nil];
    }];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^(){
    }];
}
- (void)dismissContactView {
    [grayView removeFromSuperview];
}

#pragma mark - ---------- 懒加载 ----------
- (ICN_HeadImageSelView *)changeHeadImageView {
    if (!_changeHeadImageView)
    {
        _changeHeadImageView = [[NSBundle mainBundle] loadNibNamed:@"ICN_HeadImageSelView" owner:self options:nil].lastObject;
    }
    return _changeHeadImageView;
}
//完成
- (void)sureClick{

    
     [self modifyMessages];
}








@end
